const Log = require('../models/Log');

// 获取所有日志
const getAllLogs = async (req, res) => {
  try {
    const logs = await Log.getAll();
    res.json({
      success: true,
      data: logs
    });
  } catch (error) {
    console.error('获取日志失败:', error);
    res.status(500).json({
      success: false,
      message: '获取日志失败',
      error: error.message
    });
  }
};

// 根据 ID 获取日志
const getLogById = async (req, res) => {
  try {
    const { no } = req.params;
    const log = await Log.getById(no);
    
    if (!log) {
      return res.status(404).json({
        success: false,
        message: '日志不存在'
      });
    }
    
    res.json({
      success: true,
      data: log
    });
  } catch (error) {
    console.error('获取日志失败:', error);
    res.status(500).json({
      success: false,
      message: '获取日志失败',
      error: error.message
    });
  }
};

// 创建新日志
const createLog = async (req, res) => {
  try {
    const { name } = req.body;
    if (!name) return res.status(400).json({ success: false, message: '名称不能为空' });
    const newTool = await Log.create({ name });
    res.json({ success: true, data: newTool });
  } catch (error) {
    res.status(500).json({ success: false, message: '新增失败', error: error.message });
  }
};

// 更新日志
const updateLog = async (req, res) => {
  try {
    const { no } = req.params;
    const { uuid, name } = req.body;
    
    if (!uuid || !name) {
      return res.status(400).json({
        success: false,
        message: 'uuid 和 name 都是必填字段'
      });
    }
    
    const success = await Log.update(no, { uuid, name });
    
    if (!success) {
      return res.status(404).json({
        success: false,
        message: '日志不存在'
      });
    }
    
    const updatedLog = await Log.getById(no);
    
    res.json({
      success: true,
      data: updatedLog,
      message: '日志更新成功'
    });
  } catch (error) {
    console.error('更新日志失败:', error);
    res.status(500).json({
      success: false,
      message: '更新日志失败',
      error: error.message
    });
  }
};

// 删除日志
const deleteLog = async (req, res) => {
  try {
    const { no } = req.params;
    const success = await Log.delete(no);
    
    if (!success) {
      return res.status(404).json({
        success: false,
        message: '日志不存在'
      });
    }
    
    res.json({
      success: true,
      message: '日志删除成功'
    });
  } catch (error) {
    console.error('删除日志失败:', error);
    res.status(500).json({
      success: false,
      message: '删除日志失败',
      error: error.message
    });
  }
};

module.exports = {
  getAllLogs,
  getLogById,
  createLog,
  updateLog,
  deleteLog
}; 